package mall.repository;


import mall.core.jdbc.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;


@Deprecated
public abstract class BaseDao<T> {

    public int executeUpdate(String sql, Object... params) {
        Connection con = null;
        PreparedStatement pre = null;
        int executeUpdate;
        try {
            con = JdbcUtils.getConnection();
            pre = con.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pre.setObject(i + 1, params[i]);
            }
            executeUpdate = pre.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

            try {
                JdbcUtils.close(null, pre, con);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return executeUpdate;
    }

    public List<T> executeQuery(String sql, Object... params)  {
        Connection con = null;
        List<T> list;
        try {
            con = JdbcUtils.getConnection();
            PreparedStatement pre = con.prepareStatement(sql);
            list = new ArrayList<>();
            for (int i = 0; i < params.length; i++) {
                pre.setObject(i + 1, params[i]);
            }
            ResultSet rs = pre.executeQuery();
            while (rs.next()) {
                T obj = rowToObject(rs);
                list.add(obj);
            }
            JdbcUtils.close(rs, pre, con);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return list;
    }

    /**
     * 执行 count 查询
     */
    public Integer executeQueryCount(String sql, Object[] params) {
        Connection con = null;
        List<T> list;
        try {
            con = JdbcUtils.getConnection();
            PreparedStatement pre = con.prepareStatement(sql);
            list = new ArrayList<>();
            for (int i = 0; i < params.length; i++) {
                pre.setObject(i + 1, params[i]);
            }
            ResultSet rs = pre.executeQuery();
            if (rs.next()) {
                return rs.getInt(1);
            }
            JdbcUtils.close(rs, pre, con);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return 0;
    }

    public abstract T rowToObject(ResultSet rs) throws Exception;
}
